package com.biz.primus.ms.depot.dao.specfication;

import com.biz.primus.model.depot.vo.EmpSpreadPageReqVo;
import com.biz.primus.ms.depot.dao.po.EmpSpread;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Timestamp;
import java.util.List;

/**
 * EmpSpreadSpeccification
 *
 * @author JKLiues
 * @date 2017年11月28日
 */
@AllArgsConstructor
public class EmpSpreadSpeccification implements Specification<EmpSpread> {

    private EmpSpreadPageReqVo reqVo;

    @Override
    public Predicate toPredicate(Root<EmpSpread> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();
        if (StringUtils.isNotBlank(reqVo.getDepotCode())) {
            predicates.add(cb.equal(root.get("depotCode").as(String.class), reqVo.getDepotCode()));
        }
        if (StringUtils.isNotBlank(reqVo.getEmpCode())) {
            predicates.add(cb.equal(root.get("employeeCode").as(String.class), reqVo.getEmpCode()));
        }
        if (StringUtils.isNotBlank(reqVo.getEmpName())) {
            predicates.add(cb.like(root.get("name").as(String.class), "%" + reqVo.getDepotCode() + "%"));
        }
        Timestamp startTime = reqVo.getStartTime();
        Timestamp endTime = reqVo.getEndTime();
        if (startTime != null) {
            predicates.add(cb.greaterThanOrEqualTo(root.get("createTimestamp").as(Timestamp.class), startTime));
        }
        if (endTime != null) {
            predicates.add(cb.lessThanOrEqualTo(root.get("createTimestamp").as(Timestamp.class), endTime));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }

}